<template>
    <el-table v-show="searchpentList.length > 0" :data="searchpentList" @selection-change="handleSelectionChange" style="width: 10vw;
        
        float: left;">
        <el-table-column width="55">
            <template #default="{ row }">
                <el-radio class="radio" :label="row" v-model="patientInfo">&emsp;&emsp;&emsp;</el-radio>
            </template>
        </el-table-column>
        <el-table-column label="姓名" prop="realName" />
    </el-table>

    <el-card shadow="always" :body-style="{ padding: '20px' }" style="width: 80vw;margin: auto; margin-top: 50px;">
        <div>
            <div style="width: 10%;margin-left: 90%;">
                <el-button type="primary" size="default" @click="iretialAdd">保存</el-button>
                <el-button type="primary" size="default" @click="test">测试</el-button>
            </div>

            <div style="margin-top: 30px;">
                <el-form inline="true" :model="patientInfo" ref="form" label-width="80px" size="normal">
                    <el-form-item>
                        患者姓名：
                        <el-input v-model="patientInfo.realName" @input="handleInput"></el-input>
                    </el-form-item>
                    <el-form-item>
                        患者卡号：
                        <el-input v-model="patientInfo.membershipCardNumber"></el-input>
                    </el-form-item>
                    <el-form-item>
                        患者年龄：
                        <el-input v-model="patientInfo.age"></el-input>
                    </el-form-item>
                    <el-form-item>
                        家庭住址：
                        <el-input v-model="patientInfo.address"></el-input>
                    </el-form-item>
                    <el-form-item>
                        性别：
                        <el-input v-model="patientInfo.gender"></el-input>
                    </el-form-item>
                    <el-form-item>
                        手机号码：
                        <el-input v-model="patientInfo.phoneNumber"></el-input>
                    </el-form-item>
                    <el-form-item>
                        证件号码：
                        <el-input v-model="patientInfo.idCardNumber"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div style="float: left;display:flex;width: 80vw;">
                <el-card shadow="always" :body-style="{ padding: '20px' }" style="width: 70%;height: 70%;">
                    <template #header>
                        <div class="card-header">
                            <span>药品信息</span>
                        </div>
                    </template>
                    <el-table :data="retailList">
                        <el-table-column label="序号">
                            <template #default="scope">{{ scope.$index }}</template>
                        </el-table-column>
                        <el-table-column prop="medicineId" label="药品编码" />
                        <el-table-column prop="medicineName" label="药品名称" />
                        <el-table-column prop="medicineSpecification" label="药品规格" />
                        <el-table-column prop="medicineNum" label="数量">
                            <template #default="scope">
                                <el-input v-model="scope.row.medicineNum" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="medicineDosageFormId" label="单位" />
                        <el-table-column prop="retailPrice" label="单价" />

                        <el-table-column prop="medicineAmunod" label="总价">
                            <template #default="scope">
                                {{ scope.row.medicineAmunod = scope.row.medicineNum * scope.row.retailPrice }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button style=" padding: 3px 0" type="text" @click="deleted(scope.row.medicineId)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" size="default" @click="add" style="margin-left: 41%;">添加药品</el-button>
                    <template #footer>
                        <el-button type="primary" size="default" @click="changeAttach">附加费用</el-button>
                        <span style="margin-left: 20px;">附加费用价格：{{ getAttachPrice() }}</span>
                        <span style="margin-left: 20px;">操作员：</span>
                        <el-select v-model="opvalued" placeholder="业务员" style="width: 100px ;">
                            <el-option v-for="item in opvalueds" :key="item.userId" :label="item.userName"
                                :value="item.userId" @click="opvalueder">
                            </el-option>
                        </el-select>
                        <span style=" margin-left: 60%;">总价<span style="color: #f60505;">{{ allAmont = num()
                        }}</span>元</span>
                    </template>
                </el-card>
                <div style="width: 25%; height: 70vh;  margin-left: 30px;">
                    <Ranking name="nmsl" @my-event="customHandler"></Ranking>

                </div>
            </div>
        </div>
        <!-- 附加费用 -->
        <el-dialog title="" v-model="attach" width="40%">
            <template #header>

                附加费用
            </template>
            <el-table ref="tableRef" @selection-change="handleSelectionChange" :data="attachList" row-key="id">
                <el-table-column type="selection" width="55" :reserve-selection="true" />
                <el-table-column label="序号" type="index" />
                <el-table-column label="项目编号" property="id" />
                <el-table-column label="项目名" property="itemName" />
                <el-table-column label="价格" property="retailPrice" />
                <el-table-column prop="attNum" label="数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.attNum" />
                    </template>
                </el-table-column>
                <el-table-column label="单位" align="center" prop="unit">
                    <template #default="scope">
                        <dict-tag :options="sys_exam_unit" :value="scope.row.unit" />
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <span>
                    <el-button type="primary" @click="confirmAttach">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 添加药品信息 -->
        <el-dialog title="   添加药品" v-model="attachmedic" width="40%">
            <template #header>
                添加药品
                <el-input v-model="query.Name" placeholder="请输入药品名" style="width: 20%;"></el-input>
                <el-input v-model="query.type" placeholder="请输入药类别" style="width: 20%;"></el-input>
                <el-button type="primary" size="default" @click="getmedicInfo">检索</el-button>

            </template>
            <el-table row-key="medicineId" ref="tableMedicRef" :data="medicList" @selection-change="MedicSelectionChange">
                <el-table-column type="selection" width="55" :reserve-selection="true" />
                <el-table-column label="序号" type="index" />
                <el-table-column label="药品编号" property="medicineId" />
                <el-table-column label="药品名" property="medicineName" />
                <el-table-column label="药品类别" property="prescriptionName" />
                <el-table-column label="规格" property="medicineSpecification" />
                <el-table-column label="厂家" property="manufacturerName" />
                <el-table-column label="价格" property="retailPrice" />
                <el-table-column label="单位" property="medicineDosageFormId" />
            </el-table>

            <template #footer>
                <span>
                    <el-button type="primary" @click="confirmMedic">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script lang="ts" setup name="Retail">
import { reactive, ref, onMounted } from 'vue';
import { listJob } from "../../api/statistics/test";
import { retialAdd, getEx, listMedic, getP, getOper } from "../../api/statistic/statistic";
import Ranking from '../../components/ranking/index.vue'
const { proxy } = getCurrentInstance();
const { sys_exam_unit } = proxy.useDict('sys_exam_invoice', 'sys_status_type', 'sys_exam_unit', 'sys_exam_project');

// 删除已添加药品
const deleted = (datad) => {
    // 删除总体已添加药品
    retailList.value.forEach((item,index)=>{
        if(item.medicineId == datad){
            retailList.value.splice(index, 1)
        }
    })
    // 删除已添加排行药品
    rankingadded.value.forEach((item,index)=>{

        if(item.medicineId == datad){
            rankingadded.value.splice(index, 1)
        }
    })

}

//  排行组件要药品添加
const customHandler = (val) => {
    let flag = true;
    rankingadded.value.forEach(item => {
        if (val.value.medicineId == item.medicineId) {
            flag = false;
        }
    })
    if (flag) {
        let obj = Object.assign({ "medicineAmunod": 0, "medicineNum": 1 }, val.value);
        rankingadded.value.push(obj)
        retailList.value.push(obj)
    } else {
        alert("药品已添加")
    }

}
// 已添加排行药品
const rankingadded = ref([] as any);
// 查询患者信息存储
const searchpentList = ref([] as any)

let key = ref('')
// 窗口防抖
const handleInput = debounce(value => {
    key.value = value
    getPV(value)

}, 1500)


function debounce(cb, delay) {
    let timer
    return function (...args) {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            cb.call(this, ...args)
        }, delay)
    }
}

// 附加费用对话框显示
const attach = ref(false);
// 添加药品信息对话框
const attachmedic = ref(false);
const tableRef = ref();
const tableMedicRef = ref();
// 药瓶检索参数
const query = ref({
    type: "",
    Name: ""
})

const patientInfo = ref({})
// 已选择操作人员信息
const opvalued = ref('')
const opvalueder = async () => {
    await opvalueds.value.forEach(item => {
        if (opvalued.value == item.userId) {
            nm.value = item;
            console.log(nm.value);

        }
    })
}
const nm = ref({});
const allAmont = ref(0)
// 计算所有的总价
const num = () => {
    let temp = 0;
    retailList.value.forEach(element => {
        temp = temp + element.medicineAmunod
    });
    temp = temp + getAttachPrice();
    return temp;
}

// 接收后端操作员信息
const opvalueds = ref([])
// 已添加药品信息
// {
//     medicineId: "12",
//     medicineName: "牛逼药",
//     retailSpec: "牛逼规格",
//     medicineNum: 1,
//     retailUnit: "打",
//     medicinePrice: 12,
//     medicineAmunod: 0
// },
const retailList = ref([] as any);

// 接收后端药品信息
const medicList = ref([])

// 接收后端检查项目信息
const attachList = ref([])

// 已添加检查项目
const addedAttach = ref([])

const retialAddData = ref({
    // 患者信息
    patient: {} as any,
    // 药品信息
    retailMedicine: [] as any,
    // 附加项目信息
    retailAtt: [] as any,
    shoudPrice: "",
    realPrice: "",
    opvalue: {}

})

// 发起添加请求
const iretialAdd = async () => {
    addedAttach.value.forEach(item => {
        item.retailPrice = item.attNum * item.retailPrice;
    })
    retialAddData.value.retailAtt = addedAttach.value;
    retialAddData.value.retailMedicine = retailList.value;
    retialAddData.value.patient = patientInfo.value;
    retialAddData.value.opvalue = nm.value;
    retialAddData.value.shoudPrice = allAmont.value + "";
    retialAddData.value.realPrice = retialAddData.value.shoudPrice;

    const res = await retialAdd(retialAddData.value);
    if (res.code == 200) {
        addedAttach.value = [];
        retailList.value = [];
        patientInfo.value = {};
        allAmont.value = 0;
        retialAddData.value.shoudPrice = '';
    } else {
        addedAttach.value.forEach(item => {
            item.retailPrice = item.retailPrice / item.attNum;
        })
    }
}
// 附加费用对画框显示
const changeAttach = () => {
    getExv()
    attach.value = !attach.value;
}
// 已选中附加项目赋值
const handleSelectionChange = (value) => {
    addedAttach.value = value;
}
// 修改已选择药品信息
const MedicSelectionChange = (value) => {
    console.log(value);
    value.forEach(ietm => {
        let flag = true;
        retailList.value.forEach(temp => {
            if (ietm.medicineId == temp.medicineId) {
                flag = false;
            }
        })
        if (flag) {
            let obj = Object.assign({ "medicineAmunod": 0, "medicineNum": 1 }, ietm);
            obj.medicineAmunod = 0;
            retailList.value.push(obj)
        }
    })
    retailList.value.forEach((item, index) => {
        let flag = false;
        value.forEach(itemv => {
            if (itemv.medicineId == item.medicineId) {
                flag = true;
            }
        })
        if (!flag) {
            retailList.value.splice(index, 1)
        }
    })

}
// 添加药瓶确认回调函数
const confirmMedic = () => {
    attachmedic.value = !attachmedic.value;
    console.log(retailList.value);

}
// 确认添加附加费用回调
const confirmAttach = () => {
    attach.value = !attach.value;
}
// 附加费用计算
const getAttachPrice = () => {
    let num = 0;
    addedAttach.value.forEach(element => {
        num = num + element.retailPrice * element.attNum;
    });
    return num;
}
const p = {
    "curentPage": 1,
    "size": 10
}
const test = async () => {
    listJob(p)


}
// 模糊查询患者信息
const getPV = async (value) => {

    if (value == null || value == "") {
        searchpentList.value = []
    } else {
        const r = await getP(value);

        searchpentList.value = r.data;

        console.log(searchpentList.value);
    }


}
// 添加药品对话框
const add = () => {
    getmedicInfo();
    attachmedic.value = !attachmedic.value;
}
// 获取分类信息
const getExv = async () => {
    const res = await getEx();
    let data = [] as any
    res.data.forEach(item => {
        item.attNum = 1;
        data.push(item)
    })
    attachList.value = data;
}
// 获取药品信息
const getmedicInfo = async () => {
    const res = await listMedic(query.value);
    medicList.value = res.data
}
// 获取操作人员
const getOperV = async () => {
    let res = await getOper();
    opvalueds.value = res.data
}
getOperV()
</script>

<style scoped></style>